package com.cloudbroker.bsc.common.search.elasticsearch;

import com.cloudbroker.bsc.common.search.common.SearchEngineUtil;
import com.cloudbroker.bsc.common.search.core.SearchEngineBase;
import com.cloudbroker.bsc.common.search.core.SearchEngineEntity;

import org.elasticsearch.action.search.SearchResponse;

import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/**
 * Created by moyin18602 on 2016/6/14.
 */
public class ElasticsearchAdapter implements SearchEngineBase{
    private static ElasticsearchBase elasticsearchBase;

    public ElasticsearchAdapter(){
        synchronized (ElasticsearchAdapter.class) {
            if(elasticsearchBase == null){
                elasticsearchBase = new ElasticsearchBase();
            }
        }
    }

    /**
     *
     * @param database_name
     * @param table_name
     * @param row_id
     * @param map
     * @return
     */
    public <T> boolean save(String database_name, String table_name, String row_id, T obj){
        return elasticsearchBase.save(database_name,table_name,row_id,obj);
    }

    /**
     *
     * @param list
     * @param <T>
     * @return
     */
    public <T> boolean save(List<T> list){
        return elasticsearchBase.save(list);
    }

    /**
     *
     * @param entity
     * @return
     */
    public boolean save(SearchEngineEntity entity){
        return elasticsearchBase.save(entity);
    }

    /**
     *
     * @param database_name
     * @param table_name
     * @param row_id
     * @param map
     * @return
     */
    public <T> boolean update(String database_name, String table_name, String row_id, T obj){
        return elasticsearchBase.update(database_name,table_name,row_id,obj);
    }

    /**
     *
     * @param entity
     * @return
     */
    public boolean update(SearchEngineEntity entity){
        return elasticsearchBase.update(entity);
    }

    /**
     *
     * @param database_name
     * @param table_name
     * @param row_id
     * @return
     */
    public boolean delete(String database_name, String table_name, String row_id){
        return elasticsearchBase.delete(database_name,table_name,row_id);
    }

    /**
     *
     * @param entity
     * @return
     */
    public boolean delete(SearchEngineEntity entity){
        return elasticsearchBase.delete(entity);
    }

    @Override
    public <T> List<Map> query(T entity) {
        SearchResponse searchResponse = elasticsearchBase.query((ElasticsearchEntity)entity);

        return SearchEngineUtil.searchHistsToList(searchResponse.getHits());
    }

	@Override
	public Object deleteAll() {
		
			Object s = null;
			try {
				s = elasticsearchBase.deleteAll();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return s;
		
		
	}
}
